import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('./images/IMG_8799.JPG')
img = cv2.resize(img,(600,800))
OLD_IMG = img.copy()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)

mask = np.zeros(img.shape[:2], np.uint8)
SIZE = (1, 65)
bgdModle = np.zeros(SIZE, np.float64)
fgdModle = np.zeros(SIZE, np.float64)

circles = cv2.HoughCircles(blur, cv2.HOUGH_GRADIENT, 1, 50,
                               param1=100, param2=30, minRadius=30, maxRadius=50)
print(circles)
rect = (int(circles[0][0][0])-1*int(circles[0][0][2]), int(circles[0][0][1])-11*int(circles[0][0][2]), 2*int(circles[0][0][2]), 22*int(circles[0][0][2]))


cv2.rectangle(OLD_IMG, (int(circles[0][0][0])-1*int(circles[0][0][2]),int(circles[0][0][1])-11*int(circles[0][0][2])),
              (int(circles[0][0][0]) + 1 * int(circles[0][0][2]), int(circles[0][0][1]) + 11 * int(circles[0][0][2])), (0, 255, 0), 2, 4)

cv2.grabCut(img, mask, rect, bgdModle, fgdModle, 10, cv2.GC_INIT_WITH_RECT)

mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
img *= mask2[:, :, np.newaxis]

plt.subplot(121), plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
plt.title("grabcut"), plt.xticks([]), plt.yticks([])
plt.subplot(122), plt.imshow(cv2.cvtColor(OLD_IMG, cv2.COLOR_BGR2RGB))
plt.title("original"), plt.xticks([]), plt.yticks([])

plt.show()